package jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import handler.ResultHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtil {
    private static final DruidDataSource ds = new DruidDataSource();
    /*
    * 初始化数据源
    * @param props
    * */
    public static void initDataSource(Properties prop) {
        ds.configFromPropety(prop);
    }

    /*
    * 销毁数据源
    * */
    public static void destroyDataSource() {
        ds.close();
    }

    public static <T> T query(String sql, ResultHandler<T> handler, Object... params) {
        try {
            Connection conn = ds.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            if(params.length > 0 && params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            ResultSet rs = ps.executeQuery();
            T t = handler.handle(rs);
            rs.close();
            ps.close();
            conn.close();
            return t;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int update(String sql,Object... params){
        Connection conn = null;
        try {
            conn = ds.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            if(params.length > 0 && params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            int affectedRows = ps.executeUpdate();
            conn.commit();
            ps.close();
            conn.close();
            return affectedRows;
        }catch (Exception e){
            e.printStackTrace();
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
        return -1;
    }

}
